﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;



namespace Alos.Common
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AlosAuthAttribute : ActionFilterAttribute
    {
        #region 构造函数
        private Enumerate.UserType ut;
        public AlosAuthAttribute(Enumerate.UserType _ut)
        {
            ut = _ut;
        }
        #endregion
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("ControllerContext");

            var attrs = filterContext.ActionDescriptor.GetCustomAttributes<MethodDescriptionAttribute>();
            var isViewPage = attrs.Count >= 1; //当前Action请求是否为具体的功能页

            List<MethodDescriptionAttribute> lap = new List<MethodDescriptionAttribute>();

            foreach (var item in attrs)
            {
                lap.Add(item as MethodDescriptionAttribute);
            }

            if (this.AuthorizeCore(filterContext, isViewPage, lap) == false) //根据验证判断进行处理
            {
                throw (new NotLoginException("对不起，用户登录超时，请重新登录！", ut));
            }
        }
        //权限判断业务逻辑
        protected virtual bool AuthorizeCore(HttpActionContext filterContext, bool isViewPage, List<MethodDescriptionAttribute> lap)
        {
            if (filterContext.ControllerContext == null)
            {
                throw new ArgumentNullException("ControllerContext");
            }
            var userInfo = Common.Current.User;
            if (userInfo == null || userInfo.id != (int)ut)
                throw (new NotLoginException("对不起，用户登录超时，请重新登录！", ut));
            return userInfo.id > 0;
        }
    }
}
